package icu.guodapeng.oauth2.controller

import icu.guodapeng.oauth2.api.CommonResult
import icu.guodapeng.oauth2.domain.user.dto.Oauth2TokenDto
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import java.security.Principal
import org.springframework.security.oauth2.common.OAuth2AccessToken
import javax.annotation.Resource


@RestController
class AuthController {

    @Resource
    lateinit var tokenEndpoint: TokenEndpoint

    // 自定义 Oauth2 获取令牌接口
    @PostMapping("/oauth/token")
    fun postAccessToken(
        principal: Principal,
        @RequestParam parameters: Map<String, String>
    ): CommonResult<Oauth2TokenDto> {

        val oAuth2AccessToken = tokenEndpoint.postAccessToken(principal, parameters).body as OAuth2AccessToken

        return CommonResult.success(
            Oauth2TokenDto(
                oAuth2AccessToken.value,
                oAuth2AccessToken.refreshToken.value,
                "Bearer ",
                oAuth2AccessToken.expiresIn
            )
        )
    }
}
